package utils

import (
	"MoSkeleton/framework/core/config/properties_gin"
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/mo_gin"
	"errors"
	"github.com/gin-gonic/gin"
	"strings"
)

func GetJwtToken(c *gin.Context) (string, bool) {
	jwtProperty := mo_gin.CommonGin.AuthGroup.Jwt
	headerKey := jwtProperty.HeaderKey
	if headerKey == "" {
		headerKey = consts.DefaultAuth_Jwt_HeaderKey
	}
	token := c.GetHeader(headerKey)
	return token, token != ""
}

func GetBearerToken(c *gin.Context) (string, bool, error) {
	bearerProperty := mo_gin.CommonGin.AuthGroup.Bearer
	token, err := readTokenFromBearer(bearerProperty, c)
	if err != nil {
		return "", false, err
	}
	return token, token != "", nil
}

func GetOauth2Token(c *gin.Context) (string, bool) {
	headerKey := mo_gin.CommonGin.AuthGroup.Oauth2.HeaderKey
	if headerKey == "" {
		headerKey = consts.DefaultAuth_Oauth_HeaderKey
	}
	token := c.GetHeader(headerKey)
	return token, token != ""
}

func readTokenFromBearer(bearerProperty properties_gin.JwtProperty, c *gin.Context) (token string, err error) {
	headerKey := bearerProperty.HeaderKey
	if headerKey == "" {
		headerKey = consts.DefaultAuth_Bearer_Headerkey
	}
	token = c.GetHeader(headerKey)
	if token == "" || !strings.HasPrefix(token, consts.Bearer_Token_Prefix) {
		mo_gin.MoLogger.Debug("未获取到bearer token")
		return
	}
	newToken, ok := strings.CutPrefix(token, consts.Bearer_Token_Prefix)
	if !ok {
		mo_gin.MoLogger.Debug("bearer token格式错误")
		return "", errors.New("bearer token格式错误")
	}
	token = newToken
	return
}
